package cn.service.productService.ProductServiceImpl;

import cn.service.productService.ProductService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import entity.*;
import entity.productEntity.Condition;
import entity.productEntity.PmsProduct;
import entity.productEntity.ProductAttributesValue;
import entity.productEntity.Sku;
import mapper.productMapper.*;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * @author 朱颢阳
 * @description
 * @time 2024/8/23 14:08
 */
@Service
public class ProductServiceImpl implements ProductService {
    @Resource
    PmsProductMapper mapper;
    @Resource
    ProductAttributesValueMapper avmapper;
    @Resource
    ProductServiceMapper psmapper;
    @Resource
    ProductServiceMapper productServiceMapper;
    @Resource
    ProductAttributesValueMapper productAttributesValueMapper;
    @Resource
    SkuMapper skuMapper;
    @Override
    public Result getformjson(String string) {
        JSONObject jsonObject=JSONObject.parseObject(string);
        //ruleForm
        JSONObject ruleForm= (JSONObject) jsonObject.get("ruleForm");
        PmsProduct product=ruleForm.toJavaObject(PmsProduct.class);
        if (mapper.insert(product)<1){
            return Result.failed(500,"添加失败！");
        }
        Integer id=product.getProduct_id();

        //service
        JSONArray jsonArray=jsonObject.getJSONArray("service");
        List<Integer> servicelist=jsonArray.toJavaList(Integer.class);
        for (Integer integer : servicelist) {
            if(psmapper.insert(new entity.productEntity.ProductService(id,integer))<1){
                return Result.failed(500,"添加失败！");
            }
        }

        //selectedAttValues
        JSONObject jsonObject1= (JSONObject) jsonObject.get("selectedAttValues");
        Set<String> set = jsonObject1.keySet();
        ArrayList<ProductAttributesValue> arrayList = new ArrayList<>();
        //格式转换
        for (String s : set) {
            List<String> values= (List<String>) jsonObject1.get(s);
            System.out.println("values=>"+values);
            if (values.size()!=0){
                for (String value : values) {
                    arrayList.add(new ProductAttributesValue(id,s,value));
                }
            }
        }
        int count=0;
        for (ProductAttributesValue productAttributesValue : arrayList) {
            if (avmapper.insert(productAttributesValue)>0){
                count++;
            }else{
                return Result.failed(500,"添加失败！");
            }
        }

        //sku
        JSONArray skuJsonArray=jsonObject.getJSONArray("tableData");
        List<Sku> skus=skuJsonArray.toJavaList(Sku.class);
        for (Sku sku1 : skus) {
            sku1.setProduct_id(id);
            if (skuMapper.selectByPrimaryKey(sku1.getSku_code())>0){
             //存在，更新
                if(skuMapper.updateByPrimaryKey(sku1)>0){

             }else{
                return Result.failed(500,"sku同步失败！");
            }
            }else {
             //不存在，新增
             if(skuMapper.insertSelective(sku1)>0){

                }else{
                return Result.failed(500,"sku同步失败！");
                }
            }
        }
        return Result.success("添加成功");
    }
    @Override
    public Result updateformjson(String string) {
        JSONObject jsonObject=JSONObject.parseObject(string);
        //ruleForm
        JSONObject ruleForm= (JSONObject) jsonObject.get("ruleForm");
        PmsProduct product=ruleForm.toJavaObject(PmsProduct.class);
        if (mapper.updateByPrimaryKeySelective(product)<1){
            return Result.failed(500,"修改失败！");
        }
        Integer id=product.getProduct_id();

        //service
        psmapper.deleteByPrimaryKey(id);
        JSONArray jsonArray = jsonObject.getJSONArray("service");
        List<Integer> servicelist = jsonArray.toJavaList(Integer.class);
        for (Integer integer : servicelist) {
            if (psmapper.insert(new entity.productEntity.ProductService(id, integer)) < 1) {
                return Result.failed(500, "修改失败！");
            }
        }

        //selectedAttValues
        avmapper.deleteByPrimaryKey(id);
        JSONObject jsonObject1= (JSONObject) jsonObject.get("selectedAttValues");
        Set<String> set = jsonObject1.keySet();
        ArrayList<ProductAttributesValue> arrayList = new ArrayList<>();
        //格式转换
        for (String s : set) {
            List<String> values= (List<String>) jsonObject1.get(s);
            System.out.println("values=>"+values);
            if (values.size()!=0){
                for (String value : values) {
                    arrayList.add(new ProductAttributesValue(id,s,value));
                }
            }
        }
        int count=0;
        for (ProductAttributesValue productAttributesValue : arrayList) {
            if (avmapper.insert(productAttributesValue)>0){
                count++;
            }else{
                return Result.failed(500,"修改失败！");
            }
        }
        //sku
        JSONArray skuJsonArray=jsonObject.getJSONArray("tableData");
        // 处理每个 JSON 对象
        for (int i = 0; i < skuJsonArray.size(); i++) {
            JSONObject skuJson = skuJsonArray.getJSONObject(i);
            // 获取所有字段及其值
            StringBuilder valueBuilder = new StringBuilder();

            for (String key : skuJson.keySet()) {
                Object fieldValue = skuJson.get(key);
                if (!key.equals("sku_id") &&
                        !key.equals("product_id") &&
                        !key.equals("sku_code") &&
                        !key.equals("promotion_price") &&
                        !key.equals("stock") &&
                        !key.equals("low_stock") &&
                        !key.equals("sale_price")) {

                    if (fieldValue != null) {
                        valueBuilder.append(key).append(":").append(fieldValue.toString()).append(";");
                    }
                }
            }
            // 设置 value 字段
            skuJson.put("value", valueBuilder.toString());
        }
        List<Sku> skus=skuJsonArray.toJavaList(Sku.class);
        for (Sku sku1 : skus) {
            sku1.setProduct_id(id);
            if (skuMapper.selectByPrimaryKey(sku1.getSku_code())>0){
                //存在，更新
                if(skuMapper.updateByPrimaryKey(sku1)>0){

                }else{
                    return Result.failed(500,"sku同步失败！");
                }
            }else {
                //不存在，新增
                if(skuMapper.insertSelective(sku1)>0){

                }else{
                    return Result.failed(500,"sku同步失败！");
                }
            }
        }
        return Result.success("修改成功");
    }

    @Override
    public Result getproducts(Condition condition) {
        PageHelper.startPage(condition.getCurrentPage(),condition.getPageSize());
        Page<PmsProduct> page= (Page<PmsProduct>) mapper.getproducts(condition);
        return Result.success((int)page.getTotal(),page.getResult());
    }

    @Override
    public Result updatepublish_status(Integer id, Integer value) {
        if (mapper.updatepublish_status(id, value)>0){
            return Result.success("更新成功");
        }else{
            return Result.failed(200,"更新失败！");
        }
    }

    @Override
    public Result updatenew_status(Integer id, Integer value) {
        if (mapper.updatenew_status(id, value)>0){
            return Result.success("更新成功");
        }else{
            return Result.failed(200,"更新失败！");
        }
    }

    @Override
    public Result updaterecommand_status(Integer id, Integer value) {
        if (mapper.updaterecommand_status(id, value)>0){
            return Result.success("更新成功");
        }else{
            return Result.failed(200,"更新失败！");
        }
    }

    @Override
    public Result deleteproduct(Integer id) {
        if (mapper.deleteByPrimaryKey(id)>0){
            return Result.success("删除成功");
        }else{
            return Result.failed(200,"删除失败！");
        }
    }
    @Override
    public Result getproductinfo(Integer id) {
        return Result.success(200,mapper.selectByPrimaryKey(id));
    }
    @Override
    public Result getserviceinfo(Integer id) {
        return Result.success(200,productServiceMapper.selectByPrimaryKey(id));
    }
    @Override
    public Result getattributeinfo(Integer id) {
        List<ProductAttributesValue> attributesValues = productAttributesValueMapper.selectByPrimaryKey(id);
        Set<String> set =new HashSet<>();
        for (ProductAttributesValue value : attributesValues) {
            set.add(value.getAttribute_name());
        }
        JSONObject jsonObject=new JSONObject();
        for (String s : set) {
            List<String> values=new ArrayList<>();
            for (ProductAttributesValue value : attributesValues) {
                if (Objects.equals(s,value.getAttribute_name())){
                    values.add(value.getValue());
                }
            }
            jsonObject.put(s,values);
        }
        return Result.success(200,jsonObject);
    }
}
